"""
读取并解析 gd32_data.xlsx文件
"""
import pandas as pd

# 0 1 2 3 4 5 6 7 8 9 10 11 12 13
# A B C D E F G H I J K  L  M  N

# 定义字母和索引对照表
LETTER_INDEX = {
    'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13   
}

def main():
    
    # 打开文件outout.csv
    f = open('output.csv', 'w')
    
    # 读取gd32.xlsx文件
    pd_data = pd.read_excel('gd32f407.xlsx')
    # 提取Sheet1的前C-M列数据
    pd_data = pd_data.iloc[:, :10]
    # print(pd_data)
    for i in range(len(pd_data)):
        flag = pd_data.iloc[i, 0]
        # 如果dat是None或nan或非1.0则跳过
        if flag == None or "" == flag or pd.isna(flag) or flag!= 1.0:
            # print("无数据")
            continue
        
        # 取出2列数据, 逐个去除内容里的空格
        # print(pd_data.iloc[i, 2])
        pin_name = pd_data.iloc[i, LETTER_INDEX["B"]]
        if type(pin_name) == str:
            pin_name = pin_name.replace(' ', '').replace('\n', '')
        
        # 取出3列内容，作为pins
        pins = pd_data.iloc[i, LETTER_INDEX["C"]]
        if type(pins) == str:
            pins = pins.replace(' ', '').replace('\n', '')
        
        
        # 取出F列内容，作为描述
        desc:str = pd_data.iloc[i, LETTER_INDEX["F"]]
        additional = "-"
        if type(desc) == str:
            desc = desc.replace(' ', '').replace('\n', '')
            desc = desc.replace("Default:","", 1)
            
            add_index = desc.rfind("Additional:")
            if add_index!= -1:
                additional = desc[add_index:]
                additional = additional.removeprefix("Additional:")
                additional = additional.replace(",", "|")
                
                desc = desc[:add_index]
            
            desc = desc.split('Alternate:')
    
        default_desc = desc[0]
        default_desc = default_desc.replace(pin_name, "").replace(",", "|")
        # 将pins中连续的|替换成一个|
        default_desc = default_desc.replace("||", "|")
        default_desc = default_desc.removeprefix("|")
        default_desc = default_desc.removesuffix("|")
        if default_desc == "":
            default_desc = "-"
        
        content = "".join(desc[1:]).replace(",", "|")
        if content == "":
            content = "-"
            
        content_lst = content.split("|")
        
        timers = filter_content(content_lst, lambda item: "TIMER" in item)
        usarts = filter_content(content_lst, lambda item: "USART" in item or "UART" in item)
        i2cs   = filter_content(content_lst, lambda item: "I2C" in item)
        i2ss   = filter_content(content_lst, lambda item: "I2S" in item)
        spis   = filter_content(content_lst, lambda item: "SPI" in item)
        exmc   = filter_content(content_lst, lambda item: "EXMC" in item)
        enet   = filter_content(content_lst, lambda item: "ENET" in item)
        usbhs  = filter_content(content_lst, lambda item: "USB" in item)
        tli    = filter_content(content_lst, lambda item: "TLI" in item)
        dci    = filter_content(content_lst, lambda item: "DCI" in item)
        sdio   = filter_content(content_lst, lambda item: "SDIO" in item)
        eventout = filter_content(content_lst, lambda item: "EVENT" in item)
        can = filter_content(content_lst, lambda item: "CAN" in item)
        
        content = "|".join(content_lst)
        
        line = f"{pin_name},{pins},{default_desc},"
        line += f"{timers},{usarts},{i2cs},{i2ss},{spis},{exmc},{enet},{usbhs},{tli},{dci},{sdio},{can},{eventout},"
        line += f"{content},{additional}"
        print(line)
        
        f.write(line + "\n")
        
    print("len: ", len(pd_data))
    f.close()

def filter_content(content_lst: list, filter):
    peripherals = [item for item in content_lst if filter(item)]
    for item in peripherals: 
        content_lst.remove(item)
    peripherals = "|".join(peripherals)
    return peripherals



if __name__ == '__main__':
    main()
